<template>
  <div id="rptresult">
    <div style="height: calc(100% - 30px)">
      <vxe-table show-overflow keep-source ref="tableResultRef" height="auto" :row-config="{ height: resultRowHeight, isCurrent: true, isHover: true }" :header-cell-style="{ height: '28px', padding: '0px 2px' }" :column-config="{ resizable: true }" :loading="loading" :data="resultList" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false, showIcon: false, enabled: rptMaininfo.isChk === 0 || rptMaininfo.isChk === '0' || rptMaininfo.isChk === null || rptMaininfo.isChk === undefined }" :cell-style="calcCellBgColor" :menu-config="rightMenuConfig" @menu-click="contextMenuClickEvent" :tooltip-config="tooltipConfig">
        <vxe-column type="checkbox" width="30" fixed="left" align="center" v-if="rptMaininfo.isChk === 0 || rptMaininfo.isChk === '0' || rptMaininfo.isChk === null || rptMaininfo.isChk === undefined"></vxe-column>
        <vxe-column type="seq" width="24" fixed="left"></vxe-column>

        <vxe-column :field="colitem.fieldCode" :title="colitem.fieldName" :sortable="colitem.isSortable === 1" :fixed="colitem.isFix === 1 ? 'left' : ''" :width="colitem.columnWidth" v-for="(colitem, index) in rptResultColumns.filter((data) => data.isVisiable == 1)" :key="index" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #header>
            <span v-if="colitem.fieldCode === 'isContrast'" style="font-size: 300">
              <el-icon>
                <WarningFilled />
              </el-icon>
            </span>
            <span v-else style="font-size: 300">{{ colitem.fieldName }}</span>
          </template>
          <template #edit="{ row, rowIndex }">
            <div v-if="colitem.fieldCode === 'isContrast'">
              <!-- 多少度 -->
              <span class="el-icon-warning" v-if="row.isContrast === '0' || row.isContrast === 0">
                <el-icon>
                  <WarningFilled />
                </el-icon>
              </span>
            </div>
            <div v-if="colitem.fieldCode === 'itemNo'">
              <SelectItemGrid v-if="row.id === undefined || row.id === '' || row.id === null" :url="'/lab/rptResult/findRptResultItem'" :column="[
                  { type: 'seq', title: '#', width: 30 }, //列标题
                  { field: 'itemNo', title: '编号' }, //列标题
                  { field: 'itemNa', title: '名称' }
                ]" :searchParam="{ rptGroup: rptMaininfo.rptGroup, enable: 1 }" :isPage="false" @SelectCellClick="(e) => {
  SelectRowClick(e, rowIndex);
}
  "></SelectItemGrid>
              <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap" v-else>
                {{ row.itemNo + ' ' + row.itemNa + (row.itemUnit !== null && row.itemUnit !== undefined && row.itemUnit
                  !== '' ? ' ' + row.itemUnit : '') }}
              </div>
            </div>
            <div v-if="colitem.fieldCode === 'testResult'">
              <vxe-pulldown :ref="'xDown5' + rowIndex" transfer style="width: 100%">
                <template #default>
                  <!-- 修改 -->
                  <!-- <vxe-input class="wl-result-exmitem" :ref="'wlResult' + rowIndex" style="width: 100%; user-select: all"
                    @focus="resultFocusEcent(row, rowIndex)" @blur="resultBlurEvent(row, rowIndex)" clearable
                    v-model="row.testResult" @keyup="keyupEvent5(row, rowIndex, $event)"
                    @dblclick.native.prevent="resultDBClickEvent(row, rowIndex, $event)"></vxe-input> -->
                  <vxe-input class="wl-result-exmitem" :ref="'wlResult' + rowIndex" style="width: 100%; user-select: all" @focus="resultFocusEcent(row, rowIndex)" @blur="resultBlurEvent(row, rowIndex)" clearable v-model="row.testResult" @keyup="keyupEvent5(row, rowIndex, $event)" @dblclick.native.prevent="resultDBClickEvent(row, rowIndex, $event)"></vxe-input>
                </template>
                <template #dropdown>
                  <div class="my-dropdown5" style="text-align:right;">
                    <vxe-button style="margin:5px;" v-if="showBigTextFlag" type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveBigTextResult(row,rowIndex)"></vxe-button>
                    <vxe-textarea v-if="showBigTextFlag" v-model="bigTextResult" placeholder="结果" :autosize="{ minRows: 7 }"></vxe-textarea>
                    <vxe-grid :ref="'gridTable' + rowIndex" border auto-resize height="auto" :row-config="{ isHover: true, isCurrent: true }" :keyboard-config="{ isArrow: true, isEnter: true }" :data="tableData5" :columns="tableColumn5" @cell-click="cellClickEvent5(row, rowIndex, $event)"></vxe-grid>
                  </div>
                </template>
              </vxe-pulldown>
            </div>
            <div v-if="colitem.fieldCode !== 'itemNo' && colitem.fieldCode !== 'testResult' && colitem.fieldCode !== 'isContrast'">
              {{ row[colitem.fieldCode] }}
            </div>
          </template>
          <template #default="{ row }">
            <span v-if="colitem.fieldCode === 'itemNo'">{{ row.itemNo + ' ' + row.itemNa + (row.itemUnit !== null &&
              row.itemUnit !== undefined && row.itemUnit !== '' ? ' ' + row.itemUnit : '') }}</span>
            <span v-else-if="colitem.fieldCode === 'resultFlag'">
              <span class="padding-lr-xs text-df text-bold">{{ row.exceptionSymbol === undefined || row.exceptionSymbol
                === null || row.exceptionSymbol === '' ? getResultFlag(row.resultFlag) : row.exceptionSymbol }}</span>
              <!-- <span class="padding-lr-xs" v-if="row.isAlarm === '1' || row.isAlarm === 1" :style="getAlarmText()">{{ row.alarmText }}</span> -->
            </span>
            <span v-else-if="colitem.fieldCode === 'alarmText'">
              <span class="padding-lr-xs text-bold" v-if="row.isAlarm === '1' || row.isAlarm === 1" :style="getAlarmText()">{{ row.alarmText }}</span>
            </span>

            <span v-else-if="colitem.fieldCode === 'isContrast'">
              <!-- 多少度 -->
              <span class="el-icon-warning" v-if="row.isContrast === '0' || row.isContrast === 0">
                <el-icon>
                  <WarningFilled />
                </el-icon>
              </span>
            </span>

            <span :style="row.histroy1Color" v-else-if="colitem.fieldCode === 'history1'">{{ row.history1 }}</span>
            <span :style="row.histroy2Color" v-else-if="colitem.fieldCode === 'history2'">{{ row.history2 }}</span>
            <span :style="row.histroy3Color" v-else-if="colitem.fieldCode === 'history3'">{{ row.history3 }}</span>
            <span v-else>{{ row[colitem.fieldCode] }}</span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <vxe-toolbar class-name="bg-grey light">
      <template #buttons>
        <span class="flex justify-start text-cut padding-lr-xs" style="width:46%;">
          <el-carousel height="30px" style="width:100%;" direction="vertical" indicator-position="none" :interval="3000">
            <el-carousel-item>
              <span v-if="feeVsItemDictCount !== null && feeVsItemDictCount !== '' && feeVsItemDictCount !== undefined" class="text-orange text-bold text-shadow">{{ `对照数:${feeVsItemDictCount} ` }}</span>
              <span v-if="rptMaininfo.reqPurpose" class="text-bold">检验目的:</span>
              <span v-if="rptMaininfo.reqPurpose">{{ `${rptMaininfo.reqPurpose ? rptMaininfo.reqPurpose : ''} `
              }}</span>
            </el-carousel-item>

            <el-carousel-item v-if="rptMaininfo && rptMaininfo.alarmResult && rptMaininfo.isAlarm === 1">
              <span style="color: #f56c6c">危急值：{{ rptMaininfo.alarmResult }}</span>
            </el-carousel-item>
          </el-carousel>
        </span>
        <span class="flex text-cut padding-lr-xs" style="width:46%;">
          <el-carousel height="30px" style="width:100%;" direction="vertical" indicator-position="none" :interval="3000">
            <el-carousel-item class="flex justify-end">
              <span v-if="noChannelResultList.length > 0" class="text-bold wjxmjg redClazz">未建项目结果:</span>
              <span v-if="noChannelResultList.length > 0" style="cursor:pointer" class="text-blue wjxmjg" @click="noChannelResultClick">{{ noChannelResultList.length }}</span>
            </el-carousel-item>
          </el-carousel>
        </span>
      </template>
    </vxe-toolbar>
  </div>
  <!-- 通道号设置 -->
  <el-dialog title="通道号设置" :show-close="false" v-model="showNoChannelResultDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showNoChannelResultDialog">
    <div class="tableBody" style="height: 600px">
      <vxe-table ref="noChannelTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="noChannelResultList">

        <vxe-column field="sampleNo" title="样本"></vxe-column>
        <vxe-column field="itemNo" title="通道号"></vxe-column>

        <vxe-column field="testResult" title="结果"></vxe-column>
        <vxe-column field="instrCode" title="仪器"></vxe-column>
        <vxe-column field="itemDictCode" title="报告项目">
          <template #default="{ row }">
            <vxe-select v-model="row.itemDictCode" :filterable="true" transfer clearable>
              <vxe-option v-for="instr in labItemDictList" :key="instr.itemNo" :value="instr.itemNo" :label="instr.itemNa + '(' + instr.itemNo + ')'"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>
      </vxe-table>

      <div class="dialog-footer flex right justify-end">
        <el-button type="primary" :loading="rloading" @click="saveBacthNoChannelResult('noChannelTableRef')">确定</el-button>
        <el-button @click="closeNoChannelResultDialog('noChannelTableRef')">取消</el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 知识库弹框 -->
  <vxe-modal v-model="showKnowledgeBase" id="showKnowledgeBase" class-name="showKnowledgeBase" width="100%" height="100%" min-width="460" min-height="300" destroy-on-close @hide="showKnowledgeBase = false">
    <template #title>
      <span>知识库</span>
    </template>
    <div style="width: 1000px; height: 100%; margin: 0 auto; background: #fff">
      <KnowledgeBase ref="knowledgeBaseRef"></KnowledgeBase>
    </div>
  </vxe-modal>
</template>
<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted, watch, inject, computed, defineEmits } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { DateToString, IsEmpty, sortByField } from '@/utils/common';
import { rptResultRightMenus } from './RptResultUtils.ts';
import { LabMainInfoResultFields } from '@/utils/LabMainInfoResultField.ts';
import SelectItemGrid from './SelectItemGrid.vue';
import { getOptionValueByCodeGlobalOption, getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';
import { AppStore } from '@/stores/store';
import { HttpGet } from '@/utils/fetchRequestHelper';
import { getResultHistory } from '@/utils/LabRptResultHistoryFetch';
import KnowledgeBase from '@/components/KnowledgeBaseByItem.vue';
import { calcCellDisplayColor, calcCellDisplayColorV2, calcResultFlag } from '@/utils/LabRptresultHelper';

let store = AppStore();

//暴露属性和方法
defineExpose({
  insertResults,
  getRptResultInfo,
  deleteResultItem,
  setRepetition,
  addItemDict,
  initTestList,
  getRptResult,
  getResultConfigList,
  getModuleResultList,
  quietRefreshResults,
  findFeeVsItemDictCount,
  reviewValidateVsCountIsEqual /**审核验证，项目对照，检验结果数量是否相等 */,
  printValidateVsCountIsEqual /**打印验证，项目对照，检验结果数量是否相等 */,
  resultRowHeight(res: any) {
    if (!IsEmpty(res)) {
      resultRowHeight.value = res;
    }
  }
});

const proxyEmit = defineEmits(['getRptResult', 'updateTestList', 'pushTemplate']);

let { proxy }: any = getCurrentInstance();
let blurCount = ref(0);
let loading = ref(false); //加载状态
let resultRowHeight = ref(24); //行高
let resultList: any = reactive([]); //结果列表
let noChannelResultList: any = reactive([]); //未维护通道号的结果列表
let labItemDictList: any = reactive([]);
let tableColumn5 = reactive([
  { type: 'seq', title: '#', width: '30' },
  { field: 'result', title: '常用取值' }
]);
let tableData5 = reactive([]); //常用取值数组
let itemList: any = reactive([]); //结果列表
let refreshResultData = ref(false);
let showKnowledgeBase = ref(false);
let beforeValue = ref('');
let feeVsItemDictCount = ref(''); /**申请项目报告项目 */
let historyColoum1 = ref('');
let historyColoum2 = ref('');
let historyColoum3 = ref('');
let knowledgeBaseRef: any = ref(null);
let bigTextResult = ref('');
let showBigTextFlag = ref(false);

// 当前选中标本
let rptMaininfo: any = reactive({
  id: '',
  sampleda: '',
  sampleNo: '',
  rptGroup: '',
  reqPurpose: ''
});

const tableResultRef = ref(null);
const rightMenuConfig = ref(
  rptResultRightMenus(proxy, ({ options, column, row }) => {
    if (tableResultRef.value) {
      tableResultRef.value?.setCurrentRow(row);
      tableResultRef.value?.focus();
      //handleRowClick({ row });
    }
    const isDisabled = !column;
    options.forEach((list: any) => {
      list.forEach((item: any) => {
        item.disabled = isDisabled;
      });
    });
  })
);

// 页面加载时更新结果
onMounted(() => {
  getRptResult1(); //加载报告单元列表
  //getDictDetailList(); //加载字典
});

const tooltipConfig = reactive<VxeTablePropTypes.TooltipConfig>({
  showAll: true,
  enterable: true,
  contentMethod: ({ type, column, row, items, _columnIndex }) => {
    const { field } = column;
    // 重写默认的提示内容
    if (field === 'isContrast') {
      return '没有对照申请项目';
    }
    // 其余的单元格使用默认行为
    return '';
  }
});

function getRptResultInfo(rows) {
  resultList.length = 0;
  if (IsEmpty(rows)) {
    return;
  } else {
    //console.log('row========', rows);
    const a = JSON.stringify(rows);
    const b = JSON.parse(a);
    Object.assign(resultList, b);
    //resultList.push(row);
    //console.log('resultList', resultList);
    return;
  }
}

async function insertResults(formData) {
  const data = { labRptresults: formData };
  const url = '/lab/rptResult/batchAddResultItemList';
  await proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        //appendMainInfoToList(res.data);
        //VxeMessage('保存成功', VxeNotifyType.success);
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('数据存储异常', VxeNotifyType.error);
    });
}

function getAlarmText() {
  const color = getOptionValueByCodeGlobalOption('wjzztys');
  let colorStr = { color: '#000' };
  if (color) {
    colorStr = { color: color };
  }
  return colorStr;
}

let rptResultColumns = reactive([]);

function getResultConfigList(rptGroup: any) {
  rptResultColumns.length = 0;
  if (IsEmpty(rptGroup)) {
    rptResultColumns.length = 0;
    rptResultColumns.push(...LabMainInfoResultFields());
  } else {
    const url = '/lab/wlConfig/findWlConfigByRptGroup';
    const data = {
      suitModule: '1',
      rptGroup: rptGroup,
      type: 2
    };
    proxy.$http
      .get(url, { params: data })
      .then((res: any) => {
        rptResultColumns.length = 0;
        if (res.data.length > 0) {
          rptResultColumns.push(...res.data);
        } else {
          rptResultColumns.push(...LabMainInfoResultFields());
        }
      })
      .catch((err: any) => {
        rptResultColumns.length = 0;
        rptResultColumns.push(...LabMainInfoResultFields());
      });
  }
}

// 接收父组件传值
function initTestList(repData: any, isRefreshRptResult, isCbUptMainInfo = true) {
  if (IsEmpty(repData) || !repData) {
    if (!refreshResultData.value) {
      if (!isRefreshRptResult) {
        resultList.length = 0;
      }
      return;
    }
  }
  Object.assign(rptMaininfo, repData);
  rptMaininfo.resultList = [];
  if (!refreshResultData.value) {
    if (!isRefreshRptResult) {
      resultList.length = 0;
    }
  }
  getRptResult1(isCbUptMainInfo, isRefreshRptResult);
  getIntInstrResultNoChannel();
}

function getIntInstrResultNoChannel() {
  noChannelResultList.length = 0;
  labItemDictList.length = 0;
  //根据报告单元和日期 查出为对应得数据
  let url = '/int/instrResult/findInstrResultNoChannelList';
  let obj = { rptGroup: rptMaininfo.rptGroup, sampleDaStr: rptMaininfo.sampleda, sampleNo: rptMaininfo.sampleNo };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      if (res.status.code !== 1) {
        VxeMessage('获取未对应通道号失败', VxeNotifyType.error);
      } else {
        noChannelResultList.push(...res.data.noChannelList);
        if (res.data.labItemDictList) {
          labItemDictList.push(...res.data.labItemDictList);
        }
        //deptList.push(...res.data.deptList);
        // this.setCurDeptTreeNode(this.userForm.deptId);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
let showNoChannelResultDialog = ref(false); //中间质控靶值设定弹框展示状态

function noChannelResultClick() {
  showNoChannelResultDialog.value = true;
}

let rloading = ref(false);

function closeNoChannelResultDialog() {
  showNoChannelResultDialog.value = false;
  //materialTargetList.length = 0;
}
function saveBacthNoChannelResult() {
  rloading.value = true;
  //取出所有itemDictId不为空得数据
  const bacthChannelResultList = noChannelResultList.filter((p: any) => !IsEmpty(p.itemDictCode));
  if (bacthChannelResultList.length > 0) {
    const data = { noChanneResultlList: bacthChannelResultList };
    const url = '/int/instrResult/saveBacthNoChannelResult';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        rloading.value = false;
        showNoChannelResultDialog.value = false;
        getIntInstrResultNoChannel(); // 获取检验仪器表格数据
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        rloading.value = false;
        showNoChannelResultDialog.value = false;
        VxeMessage(err, VxeNotifyType.error);
      });
  } else {
    rloading.value = false;
    VxeMessage('请选择报告项目', VxeNotifyType.error);
  }
}

// 组件
//点击选择的那一项受检单位
function SelectRowClick(row, index) {
  const idx = resultList.findIndex((item) => {
    return item.itemNo === row.itemNo;
  });

  if (idx > -1) {
    // this.handleResultRowClick(this.workResultList[idx]);
    VxeMessage('此检验项目已存在', VxeNotifyType.error);
    return;
  }
  let labRptresult = {
    sampleda: rptMaininfo.sampleda,
    rptGroup: rptMaininfo.rptGroup,
    sampleNo: rptMaininfo.sampleNo,
    maininfoId: rptMaininfo.id,
    itemNo: row.itemNo,
    itemNa: row.itemNa,
    itemDictId: row.id,
    rptResult: '',
    ref: '',
    seq: '',
    displayOrder: `${row.seq}`
  };
  if (!IsEmpty(row.defValue3)) {
    labRptresult.testResult = row.defValue3;
  }
  if (!IsEmpty(row.defValue2)) {
    labRptresult.testResult = row.defValue2;
  }
  if (!IsEmpty(row.defValue1)) {
    labRptresult.testResult = row.defValue1;
  }
  if (!IsEmpty(row.defaultVal)) {
    labRptresult.testResult = row.defaultVal;
  }
  const url = '/lab/rptResult/insertRptResult';
  proxy.$http
    .post(url, labRptresult)
    .then((res: any) => {
      //getRptResult(); // 刷新结果
      Object.assign(resultList[index], res.data);
      quietRefreshResults(() => {
        proxy.$nextTick(() => {
          const curRowIndex = resultList.findIndex((t) => t.itemNo === res.data.itemNo && t.itemNa === res.data.itemNa);
          if (curRowIndex > -1) {
            const $table = proxy.$refs.tableResultRef as any;
            $table.setEditCell(resultList[curRowIndex], 'testResult');
          }
        });
      });
      //VxeMessage(res.status.msg, VxeNotifyType.success);
      if (IsEmpty(labRptresult.maininfoId)) {
        //proxy.$emit
        proxyEmit('updateTestList', { isSelCurRow: true, isRefreshRptResult: false, mainInfoId: res.data.maininfoId });
      }
    })
    .catch((err: any) => {
      //VxeMessage(err, VxeNotifyType.error);
    });

  resultList.itemNo = row.itemNo;
  resultList.itemNa = row.itemNa;
}

/**
 *
 * @param row 修改结果
 */
function resultChange(row, index) {
  proxy.$emit('changeAuditStatus', 0);
  const found = rptMaininfo.resultList.find((obj) => obj.itemNo === row.itemNo);

  if (found) {
    found.testResult = row.testResult;
  } else {
    rptMaininfo.resultList.push(row);
  }
  console.log('rptMaininfo.resultList', rptMaininfo.resultList);

  const newTempleteList = [];
  newTempleteList.push(resultList[0]);
  resultList.forEach((element) => {
    if (!element.id && element.itemNo) {
      newTempleteList.push(element);
    }
  });
  //判断resultList里是否包含没有id的，包含走批量插入
  if (!row.id && index == 0) {
    loading.value = true;
    const url = '/lab/rptResult/updateRptResultBatchNew';
    proxy.$http
      .post(url, newTempleteList)
      .then((res: any) => {
        if (row.id) {
          quietRefreshResults();
          proxy.$emit('changeAuditStatus', 1);
          loading.value = false;
        } else {
          resultList.forEach((element) => {
            element.maininfoId = res.data.maininfoId;
          });
          //proxy.$emit
          proxyEmit('updateTestList', { isSelCurRow: true, isRefreshRptResult: true, mainInfoId: res.data.maininfoId });
          proxy.$emit('changeAuditStatus', 1);
          loading.value = false;
        }
      })
      .catch((err: any) => {
        proxy.$emit('changeAuditStatus', 1);
        loading.value = false;
        //VxeMessage(err, VxeNotifyType.error);
      });
  }
  //数据删除几条后，第一条id存在 列表存在没有id的情况时，传入第一条数据和没有id的数据批量保存
  else if (index == 0 && newTempleteList.length > 1) {
    loading.value = true;
    const url = '/lab/rptResult/updateRptResultBatchNew';
    proxy.$http
      .post(url, newTempleteList)
      .then((res: any) => {
        if (row.id) {
          quietRefreshResults();
          loading.value = false;
          proxy.$emit('changeAuditStatus', 1);
        } else {
          //proxy.$emit
          proxyEmit('updateTestList', { isSelCurRow: true, isRefreshRptResult: true, mainInfoId: res.data.maininfoId });
          loading.value = false;
          proxy.$emit('changeAuditStatus', 1);
        }
      })
      .catch((err: any) => {
        loading.value = false;
        proxy.$emit('changeAuditStatus', 1);
        //VxeMessage(err, VxeNotifyType.error);
      });
  } else {
    if (IsEmpty(row.testResult)) {
      proxy.$emit('changeAuditStatus', 1);
      return;
    }
    loading.value = true;
    const url = '/lab/rptResult/updateRptResult';
    proxy.$http.post(url, row).then((res: any) => {
      quietRefreshResults();
      loading.value = false;
      proxy.$emit('changeAuditStatus', 1);
    });

    // const url = '/lab/rptResult/updateResult';
    // proxy.$http.post(url, rptMaininfo).then((res: any) => {
    //   rptMaininfo.resultList.length = 0;
    //   quietRefreshResults();
    //   loading.value = false;
    // });
  }
}

/**
 *
 * @param row 修改参考值
 */
function refChange(row) {
  if (IsEmpty(row.ref)) {
    return;
  }
  const url = '/lab/rptResult/updateRptResult';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      getRptResult(); // 获取最右侧 质控项目设定表格数据
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function getModuleResultList(list, resultTemplateId) {
  //模板多次使用过滤掉重复的
  let datas = [];
  list.forEach((item) => {
    const data = resultList.filter((a) => a.itemNo == item.itemNo);
    const i = resultList.findIndex((p) => p.itemNo === item.itemNo);
    console.log(i);
    if (!data || data.length == 0) {
      datas.push(item);
    } else {
      Object.assign(resultList[i], item);
    }
  });
  resultList.push(...sortByField(datas, 'displayOrder', 'asc'));
  if (resultTemplateId) {
    calcNextRow(-1);
  }
}

// 查询报告项目结果
function getRptResult(isCbUptMainInfo = true, isRefreshRptResult) {
  if (!isRefreshRptResult) {
    loading.value = true;
    resultList.length = 0;
    const url = '/lab/maininfo/findRptResultByLabMaininfo';
    proxy.$http
      .get(url, { params: { id: rptMaininfo.id } })
      .then((res: any) => {
        if (res.data) {
          if (!IsEmpty(res.data) && res.data) {
            resultList.length = 0;
            resultList.push(...sortByField(res.data, 'displayOrder', 'asc'));
            getHistoryResult(resultList);
          }
        }

        // if (isCbUptMainInfo) {
        //   proxy.$emit('getRptResult', resultList);
        // }

        loading.value = false;
      })
      .catch((err: any) => {
        loading.value = false;
        VxeMessage('查询报告项目结果失败', VxeNotifyType.error);
      });
  } else {
    quietRefreshResults();
  }
}

// 查询报告项目结果判断报告单元系统参数配置 是否开启结果为空删除功能，如果开启 删除为空项目
function getRptResult1(isCbUptMainInfo = true, isRefreshRptResult) {
  proxy.$emit('changeAuditStatus', 1);
  rptResultColumns.forEach((itm, idx) => {
    if (itm.fieldCode === 'history1') {
      itm.fieldName = '历史结果1';
    }
    if (itm.fieldCode === 'history2') {
      itm.fieldName = '历史结果2';
    }
    if (itm.fieldCode === 'history3') {
      itm.fieldName = '历史结果3';
    }
  });
  if (!isRefreshRptResult) {
    loading.value = true;
    resultList.length = 0;
    const url = '/lab/maininfo/findRptResultByLabMaininfoMouted';
    proxy.$http
      .get(url, { params: { id: rptMaininfo.id } })
      .then((res: any) => {
        if (res.data) {
          if (!IsEmpty(res.data) && res.data) {
            resultList.length = 0;
            resultList.push(...sortByField(res.data, 'displayOrder', 'asc'));
            getHistoryResult(resultList);
          }
        }

        // if (isCbUptMainInfo) {
        //   proxy.$emit('getRptResult', resultList);
        // }

        loading.value = false;
      })
      .catch((err: any) => {
        loading.value = false;
        VxeMessage('查询报告项目结果失败', VxeNotifyType.error);
      });
  } else {
    quietRefreshResults();
  }
}
/**
 * 静默刷新结果列表
 *
 */
function quietRefreshResults(callback) {
  //记录下当前选中行
  const curRptResultRow = tableResultRef.value?.getCurrentRecord();
  const url = '/lab/maininfo/findRptResultByLabMaininfo';
  proxy.$http
    .get(url, { params: { id: rptMaininfo.id } })
    .then(async (res: any) => {
      if (res && res.data && res.data.length > 0) {
        res.data.forEach((e) => {
          const i = resultList.findIndex((p) => p.id === e.id);
          if (i > -1) {
            Object.assign(resultList[i], e);
          } else {
            const nullid = resultList.findIndex((x) => IsEmpty(x.id));
            if (nullid > -1) {
              Object.assign(resultList[nullid], e);
            } else {
              resultList.push(e);
            }
          }
        });
        if (tableResultRef.value) {
          await tableResultRef.value?.reloadData(resultList);
          if (curRptResultRow) {
            tableResultRef.value?.setCurrentRow(curRptResultRow);
          }
        }
        //重新排序
        await tableResultRef.value?.sort('displayOrder', 'asc');
        //proxy.$emit
        proxyEmit('getRptResult', resultList);
        if (callback) {
          callback();
        }
      }
    })
    .catch((err: any) => {
      if (callback) {
        callback();
      }
    });
}

//获取历史结果列表
function getHistoryResult(resultList) {
  const resultObj = getResultHistory(rptMaininfo.id);
  resultObj.then((aa) => {
    if (aa.status === 200) {
      const a = aa.json();
      a.then((res) => {
        if (res && res.data.length > 0) {
          resultList.forEach((element) => {
            if (res.data[0]) {
              historyColoum1.value = res.data[0].historyDate;
              const his1 = res.data[0].data.filter((p) => p.itemNo == element.itemNo);
              if (his1 && his1.length > 0) {
                element.history1 = his1[0].testResult;
                element.histroy1Color = historyCalcCellBgColor(his1[0]);
                rptResultColumns.forEach((itm, idx) => {
                  if (itm.fieldCode === 'history1') {
                    itm.fieldName = res.data[0].historyDate;
                  }
                });
              }
            }
            if (res.data[1]) {
              historyColoum2.value = res.data[1].historyDate;
              const his2 = res.data[1].data.filter((p) => p.itemNo == element.itemNo);
              if (his2 && his2.length > 0) {
                element.history2 = his2[0].testResult;
                element.histroy2Color = historyCalcCellBgColor(his2[0]);
                rptResultColumns.forEach((itm, idx) => {
                  if (itm.fieldCode === 'history2') {
                    itm.fieldName = res.data[1].historyDate;
                  }
                });
              }
            }
            if (res.data[2]) {
              historyColoum3.value = res.data[2].historyDate;
              const his3 = res.data[2].data.filter((p) => p.itemNo == element.itemNo);
              if (his3 && his3.length > 0) {
                element.history3 = his3[0].testResult;
                element.histroy3Color = historyCalcCellBgColor(his3[0]);
                rptResultColumns.forEach((itm, idx) => {
                  if (itm.fieldCode === 'history3') {
                    itm.fieldName = res.data[2].historyDate;
                  }
                });
              }
            }
          });
        }
      });
    }
  });
  return;
  const url = '/lab/maininfo/findHistoryResultByLabMaininfo';
  proxy.$http
    .get(url, { params: { id: rptMaininfo.id } })
    .then((res: any) => {
      if (!IsEmpty(res.data) && res.data.length > 0) {
        resultList.forEach((element) => {
          if (res.data[0]) {
            historyColoum1.value = res.data[0].historyDate;
            const his1 = res.data[0].data.filter((p) => p.itemNo == element.itemNo);
            if (his1 && his1.length > 0) {
              element.history1 = his1[0].testResult + getResultFlag(his1[0].resultFlag);
              element.histroy1Color = historyCalcCellBgColor(his1[0]);
            }
          }
          if (res.data[1]) {
            historyColoum2.value = res.data[1].historyDate;
            const his2 = res.data[1].data.filter((p) => p.itemNo == element.itemNo);
            if (his2 && his2.length > 0) {
              element.history2 = his2[0].testResult + getResultFlag(his2[0].resultFlag);
              element.histroy2Color = historyCalcCellBgColor(his2[0]);
            }
          }
          if (res.data[2]) {
            historyColoum3.value = res.data[2].historyDate;
            const his3 = res.data[2].data.filter((p) => p.itemNo == element.itemNo);
            if (his3 && his3.length > 0) {
              element.history3 = his3[0].testResult + getResultFlag(his3[0].resultFlag);
              element.histroy3Color = historyCalcCellBgColor(his3[0]);
            }
          }
        });
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询历史结果失败', VxeNotifyType.error);
    });
}

//?检测项目选择回车事件
//TAG1 标记文本框输入是否改变
function getItemDict() {
  itemList.length = 0;
  const url = '/lab/rptResult/findRptResultItem';

  proxy.$http
    .get(url, { params: { id: '1734521514798772226' } })
    .then((res: any) => {
      itemList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('查询报告项目失败', VxeNotifyType.error);
    });
}
//新增检验结果
function addItemDict() {
  // 如果工作列表结果中已经存在未保存的项，不可重复新增
  const res = resultList.find((item) => {
    return IsEmpty(item.id);
  });

  if (res) {
    return;
  }
  // push新的内容
  const $table = proxy.$refs.tableResultRef as any;

  const newRec = {
    sampleda: rptMaininfo.sampleda,
    rptGroup: rptMaininfo.rptGroup,
    sampleNo: rptMaininfo.sampleNo,
    maininfoId: rptMaininfo.id,
    itemNo: '',
    itemNa: '',
    testResult: '',
    ref: ''
  } as any;
  resultList.push(newRec);
  //const { row: newRow } = await $table.insert(newRec)
  $table.reloadData(resultList);
  $table.setEditRow(newRec);
  proxy.$nextTick(() => {
    setTimeout(() => {
      $table.scrollToRow(newRec);
    }, 50);
  });
  // resultList.push({});
}

//删除检验结果
function deleteResultItem() {
  const selectRows = (proxy.$refs.tableResultRef as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请选择需要删除的项目', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('确定删除数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const url = '/lab/rptResult/deleteRptResults';
        proxy.$http
          .post(url, {
            labRptResultList: selectRows,
            sampleda: rptMaininfo.sampleda,
            rptGroup: rptMaininfo.rptGroup,
            sampleNo: rptMaininfo.sampleNo,
            maininfoId: rptMaininfo.id
          })
          .then((res: any) => {
            if (res.status.code != 1) {
              VxeMessage('删除失败', VxeNotifyType.error);
            } else {
              VxeMessage('删除成功', VxeNotifyType.success);
              getRptResult();
            }
          })
          .catch((err: any) => {
            proxy.$alert(err, '提示');
          });
      });
  }
}

//复查
function setRepetition() {
  const selectRows = (proxy.$refs.tableResultRef as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请选择需要复查的项目', VxeNotifyType.warning);
    return;
  }
  const details = [];
  selectRows.forEach((row) => {
    details.push({
      resultId: row.id,
      originalResult: row.testResult,
      itemNo: row.itemNo,
      itemNa: row.itemNa,
      result: ''
    });

    // 把原结果修改为"复查"，并保存
    row.testResult = '复查';
    saveResultByRepetition(row.id, row.testResult);
  });
  proxy.$nextTick(() => {
    getRptResult();
  });
  const url = '/lab/repetition/addRepetition';
  const data = {
    rptGroup: rptMaininfo.rptGroup,
    maininfoId: rptMaininfo.id,
    repDate: DateToString(new Date()),
    repDoctor: store.userInfo.id,
    repDoctorName: store.userInfo.realname,
    detail: details
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {})
    .catch((err) => {
      VxeMessage('报告项目复查失败', VxeNotifyType.error);
    });
}

// 复查时保存
function saveResultByRepetition(id, result) {
  const url = '/lab/rptResult/updateRepetition';
  const data = {
    id: id,
    testResult: result
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {})
    .catch((err) => {
      VxeMessage('报告项目复查失败', VxeNotifyType.error);
    });
}
/**
 * 计算结果的偏高偏低
 * 报告单元参数
 *【1】主界面按以上参数显示 zjmaccsxs
 *【2】偏高结果标志 pgjgbz
 *【3】偏低结果标志 pdjgbz
 *【4】阳性结果标志 yxjgbz
 *【5】弱阳结果标志 ryxjgbz
 *【6】正常结果标志 zcjgbz
 *【7】阴性结果标志 nxjgbz
 *【8】错误结果标志 cwjgbz
 * @val 结果标志
 */
function getResultFlag(val) {
  return calcResultFlag(val);
}
/**
 * 单元格背景颜色
 *【1】是否启用系统选项颜色配置  encolorsetting
 *【2】偏高结果颜色  hresultcolor
 *【3】偏低结果颜色  lresultcolor
 *【4】阳性结果颜色  presultcolor
 *【5】正常结果颜色  mresultcolor
 *【6】弱阳性结果颜包  qresultcolor
 *【7】错误结果颜色  errresultcolor
 *【8】阴性结果颜色  nresultcolor
 *【9】结果标志颜色显示方式 jgbzysxsfs (0:背景色  1:文字颜色)
 */
function calcCellBgColor({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  if (column.property === 'isContrast') {
    if (row.isContrast === 0) {
      return { background: '#FF9900', color: '#fff' };
    }
  } else {
    return calcCellDisplayColorV2({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex });
  }
}

/** 历史结果单元格颜色
 * 单元格背景颜色
 *【1】是否启用系统选项颜色配置  encolorsetting
 *【2】偏高结果颜色  hresultcolor
 *【3】偏低结果颜色  lresultcolor
 *【4】阳性结果颜色  presultcolor
 *【5】正常结果颜色  mresultcolor
 *【6】弱阳性结果颜包  qresultcolor
 *【7】错误结果颜色  errresultcolor
 *【8】阴性结果颜色  nresultcolor
 *【9】结果标志颜色显示方式 jgbzysxsfs (0:背景色  1:文字颜色)
 */
function historyCalcCellBgColor(row) {
  /**偏高【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'H') {
    //查询系统选项偏高显示颜色   背景色还是文字颜色
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('hresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#ff0000' };
  }
  /**偏高【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'H') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('hresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#ff0000', color: '#fff' };
  }

  /**偏低【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'L') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('lresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#0035ff' };
  }
  /**偏低【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'L') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('lresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ff', color: '#fff' };
  }

  /**阳性【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'P') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('presultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#0035ff' };
  }
  /**阳性【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'P') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('presultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ff', color: '#fff' };
  }

  /**弱阳性【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'Q') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('qresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#0035ee' };
  }
  /**弱阳性【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'Q') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('qresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ee', color: '#fff' };
  }

  /**错误【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'E') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('errresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#800000' };
  }
  /**错误【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'E') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('errresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#800000', color: '#fff' };
  }

  /**正常【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'M') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('mresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#000' };
  }
  /**正常【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'M') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('mresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { color: '#000' };
  }

  /**阴性【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'N') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('nresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#000' };
  }
  /**阴性【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'N') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('nresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { color: '#000' };
  }

  /**危急值 颜色 */
  if (row && !IsEmpty(row.isAlarm) && row.isAlarm === 1 && column && column.field === 'itemNo') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    const b = getOptionValueByCodeGlobalOption('isalarmcolor');
    const d = getOptionValueByCodeGlobalOption('wjzyssfxswbjys'); /**危急值颜色显示是否为背景颜色 wjzyssfxswbjys */
    if (a === 1 || a === '1') {
      if (!IsEmpty(b)) {
        if (d && (d === '1' || d === 1)) {
          return { background: b, color: '#fff' };
        } else {
          return { color: b };
        }
      }
    }
  }
}

/**
 * 结果文本框获取焦点
 * @row 当前行
 * @index 当前行索引
 */
function resultFocusEcent(row, index) {
  proxy.$emit('changeAuditStatus', 0);
  const key = 'result1';
  row[key] = row.testResult;
  beforeValue.value = row.testResult;
  const $testResultRef = proxy.$refs['wlResult' + index] as any;
  if ($testResultRef[0]) {
    $testResultRef[0].select();
  }
}

/**
 * 结果框失去焦点了
 * @row 当前行
 * @index 当前行索引
 */
async function resultBlurEvent(row, index) {
  //计算项目失去焦点时不计算 2024-07-02 pengchong
  if (row.isCalcItem == '1') {
    return;
  }
  const $textResultPanelRef = proxy.$refs['xDown5' + index] as any;
  if ($textResultPanelRef[0] && $textResultPanelRef[0].isPanelVisible()) {
    return;
  }
  if ((row['testResult'] !== '' && row['testResult'] !== null) || row['isTemplateResult'] === 1) {
    resultChange(row, index);
  }
}

/**
 * 结果文本框获取焦点时 键盘按键事件
 * @row 当前行
 * @index 当前行索引
 * @e 事件源
 */
function keyupEvent5(row, rowIndex, e) {
  const $textResultPanelRef = proxy.$refs['xDown5' + rowIndex] as any;
  if (e.$event.keyCode === 13) {
    //【step 1】先判断常用取值弹窗是否显示
    const $textResultPanelRef = proxy.$refs['xDown5' + rowIndex] as any;
    if ($textResultPanelRef[0] && $textResultPanelRef[0].isPanelVisible()) {
      const $curGrid = proxy.$refs['gridTable' + rowIndex] as any;
      if ($curGrid[0]) {
        const txtRow = $curGrid[0].getCurrentRecord();
        row.testResult = txtRow.result;
      }
    }
    //【step 2】再进行下一行处理
    calcNextRow(rowIndex);
  }
}
/**
 * 20241217暂时关闭此功能，有时候vxe-grid设置焦点不现实，待后续完善
 * 结果文本框获取焦点时 键盘按键事件
 * @row 当前行
 * @index 当前行索引
 * @e 事件源
 */
function keyupEvent51(row, rowIndex, e) {
  const $textResultPanelRef = proxy.$refs['xDown5' + rowIndex] as any;
  //去除方向键
  if (e.$event.keyCode === 37 || e.$event.keyCode === 38 || e.$event.keyCode === 39 || e.$event.keyCode === 40) {
    return;
  }
  if (e.$event.keyCode === 13) {
    //【step 1】先判断常用取值弹窗是否显示
    //const $textResultPanelRef = proxy.$refs['xDown5' + rowIndex] as any;
    if ($textResultPanelRef[0] && $textResultPanelRef[0].isPanelVisible()) {
      const $curGrid = proxy.$refs['gridTable' + rowIndex] as any;
      if ($curGrid[0]) {
        const txtRow = $curGrid[0].getCurrentRecord();
        row.testResult = txtRow.result;
      }
    } else {
      //判断双击弹出框状态,为false时，直接通过快速录入取值，否则执行默认逻辑
      //getTextResultByQuickICode(row, rowIndex, e)
      resultDBClickEvent(row, rowIndex, e);
      return;
    }
    //【step 2】再进行下一行处理
    calcNextRow(rowIndex);
  } else {
    if ($textResultPanelRef[0] && $textResultPanelRef[0].isPanelVisible()) {
      autoMarryEvent(row, rowIndex);
      return;
    } else {
      //判断双击弹出框状态,为false时，直接通过快速录入取值，否则执行默认逻辑
      //getTextResultByQuickICode(row, rowIndex, e)
      resultDBClickEvent(row, rowIndex, e);
      return;
    }
  }
}

function autoMarryEvent(row, rowIndex) {
  const $curGrid = proxy.$refs['gridTable' + rowIndex] as any;
  $curGrid[0].reloadData(tableData5);
  $curGrid[0].setCurrentRow(tableData5[0]);
  $curGrid[0].focus();
  let selecttableData5 = [];
  //用for遍历tableData5,将元素字段quickInputCode，与输入值一致数据选中
  for (let i = 0; i < tableData5.length; i++) {
    const rowe = tableData5[i];
    console.log(rowe.result, row.testResult);
    if (rowe.result.indexOf(row.testResult) > -1) {
      // $curGrid[0].setCurrentRow(rowe);
      // $curGrid[0].focus();
      selecttableData5.push(rowe);
      continue;
    }
    if (rowe.quickInputCode === row.testResult) {
      // $curGrid[0].setCurrentRow(rowe);
      // $curGrid[0].focus();
      // break;
      selecttableData5.push(rowe);
      continue;
    }
  }
  $curGrid[0].reloadData(selecttableData5);
  //判断数组长度
  if (selecttableData5.length == 0) {
    return;
  }
  $curGrid[0].setCurrentRow(selecttableData5[0]);
  $curGrid[0].focus();
  const txtRow = $curGrid[0].getCurrentRecord();
  if (IsEmpty(txtRow)) {
    setTimeout(() => {
      autoMarryEvent(row, rowIndex);
    }, 500);
  }
}
/**
 * 文本框双击、键盘按键回车公用行数
 * 跳转下一个单元格或者添加新行处理
 */
function calcNextRow(rowIndex) {
  /*是否有下一行*/
  const isNextRow = resultList.length - 1 - rowIndex > 0;
  if (isNextRow) {
    const $table = proxy.$refs.tableResultRef as any;
    if ($table) {
      $table?.setCurrentRow(resultList[rowIndex + 1]);
      $table?.setEditCell(resultList[rowIndex + 1], 'testResult');
    }
  } else {
    /*没有下一行，新增一行，焦点获取在项目选择单元格*/
    addItemDict();
  }
}

/**
 * 结果文本框被双击事件
 * @row 当前行
 * @index 当前行索引
 * @e 事件源
 */
async function resultDBClickEvent(row, rowIndex, e) {
  showBigTextFlag.value = false;
  await tableResultRef.value?.setCurrentRow(row);
  tableData5.length = 0;
  const url = '/lab/text/result/getTextResultByitemDictId';
  proxy.$http
    .get(url, { params: { itemNo: row.itemNo, rptGroup: row.rptGroup } }) //itemDictId: row.itemDictId
    .then((res: any) => {
      if (res && res.data && res.data.length > 0) {
        res.data.forEach((e, i) => {
          e.seq = i + 1;
        });
        Object.assign(tableData5, sortByField(res.data, 'seq', 'asc'));
        const $textResultPanelRef = proxy.$refs['xDown5' + rowIndex] as any;
        if ($textResultPanelRef[0] && !$textResultPanelRef[0].isPanelVisible()) {
          $textResultPanelRef[0].showPanel();
          if (row.isBigText == 1) {
            bigTextResult.value = row.testResult;
            showBigTextFlag.value = true;
          }
          //定时执行选择
          // setTimeout(() => {
          //   autoMarryEvent(row, rowIndex);
          // },200);
          proxy.$nextTick(() => {
            const $curGrid = proxy.$refs['gridTable' + rowIndex] as any;
            if ($curGrid[0]) {
              $curGrid[0].setCurrentRow(res.data[0]);
              $curGrid[0].focus();
            }
          });
        }
      } else {
        calcNextRow(rowIndex);
      }
    })
    .catch((err: any) => {
      //不做提示
    });
}

/**
 * 快速输入获取结果
 * @row 当前行
 * @index 当前行索引
 * @e 事件源
 */
async function getTextResultByQuickICode(row, rowIndex, e) {
  // await tableResultRef.value?.setCurrentRow(row);
  tableData5.length = 0;
  const url = '/lab/text/result/getTextResultByQuickICode';
  proxy.$http
    .get(url, {
      params: {
        itemNo: row.itemNo,
        rptGroup: row.rptGroup,
        quickInputCode: row.testResult
      }
    }) //itemDictId: row.itemDictId
    .then((res: any) => {
      if (res && res.data) {
        row.testResult = res.data.result;
        calcNextRow(rowIndex);
      }
    })
    .catch((err: any) => {
      //不做提示
    });
}

/**
 * 常用取值 面板表格单元格单击事件
 * @row 当前行
 * @index 当前行索引
 * @e 事件源
 */
function cellClickEvent5(row, rowIndex, e) {
  showBigTextFlag.value = false;
  const $curGrid = proxy.$refs['gridTable' + rowIndex] as any;
  if ($curGrid[0]) {
    const txtRow = $curGrid[0].getCurrentRecord();
    if (txtRow.isBigText == '1') {
      showBigTextFlag.value = true;
      bigTextResult.value += txtRow.result;
    } else {
      showBigTextFlag.value = false;
      bigTextResult.value = '';
      row.testResult = txtRow.result;
      row.isBigText = 0;
    }
  }

  const txtRow = $curGrid[0].getCurrentRecord();
  if (txtRow.isBigText != '1') {
    const $textResultPanelRef = proxy.$refs['xDown5' + rowIndex] as any;
    if ($textResultPanelRef[0] && $textResultPanelRef[0].isPanelVisible()) {
      $textResultPanelRef[0].hidePanel();
    }
    resultBlurEvent(row, rowIndex);
    calcNextRow(rowIndex);
  }
}

function saveBigTextResult(row, rowIndex) {
  row.testResult = bigTextResult.value;
  row.isBigText = 1;
  const $textResultPanelRef = proxy.$refs['xDown5' + rowIndex] as any;
  if ($textResultPanelRef[0] && $textResultPanelRef[0].isPanelVisible()) {
    $textResultPanelRef[0].hidePanel();
  }
  resultBlurEvent(row, rowIndex);
  calcNextRow(rowIndex);
}

/**右键菜单事件
 * @param menu 菜单对象
 * @param row 右键行对象
 * @param column 右键列对象
 */
function contextMenuClickEvent({ menu, row, column }) {
  switch (menu.code) {
    case 'reload':
      getRptResult();
      break; //
    case 'insertAt':
      if (!IsEmpty(rptMaininfo.isChk) && rptMaininfo.isChk >= 1) {
        VxeMessage('已审核', VxeNotifyType.warning);
        return;
      }
      addItemDict();
      break;
    case 'remove':
      if (!IsEmpty(rptMaininfo.isChk) && rptMaininfo.isChk >= 1) {
        VxeMessage('已审核', VxeNotifyType.warning);
        return;
      }
      deleteResultItem();
      break;

    case 'template':
      //proxy.$emit
      proxyEmit('pushTemplate');
      break;
    case 'transiqc':
      getQcResultByWlId(row);
      break;
    case 'knowledgeBase':
      getKnowledgeBaseData(row);
    default:
      break;
  }
}

// 获取质控物列表
function getQcResultByWlId(row) {
  //this.toQcResultModal = true;
  const data = { rptResultId: row.id };

  const url = '/api/qc/qcMaterialItemResult/transToQcResultByRptResultId';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (row) {
        (proxy.$refs.tableResultRef as any).setRadioRow(row);
      }
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
// 获取知识库数据
function getKnowledgeBaseData(row) {
  showKnowledgeBase.value = true;
  proxy.$nextTick(() => {
    knowledgeBaseRef.value?.findKnowledgeBaseByAnsList(row);
  });
}
/**申请项目、报告项目对照数量计算 */
function findFeeVsItemDictCount(reqNo: String, rptGroup: String) {
  const a = HttpGet(`${(window as any).apiUrl.VITE_SERVER_URL}/api/reqdetail/findReqDetailTotalCountByReqNo?reqNo=${reqNo}&rptGroup=${rptGroup}`);
  feeVsItemDictCount.value = '';
  a.then((res) => {
    if (res.data) {
      feeVsItemDictCount.value = `${res.data}`;
    }
  });
}
/**审核验证，项目对照，检验结果数量是否相等 */
async function reviewValidateVsCountIsEqual() {
  let res = false;
  try {
    /**对照项目、中间结果项不服是否提示的系统选项判断 jcsfxmybgxmsfxfclfs*/
    /**
     * {"label":"0","content":"不检查"},
     * {"label":"1","content":"审核时提示"},
     * {"label":"2","content":"禁止审核"},
     * {"label":"3","content":"打印时提示"},
     * {"label":"4","content":"禁止打印"},
     * {"label":"5","content":"打印审核时提示"},
     * {"label":"6","content":"禁止审核打印"},
     * {"label":"7","content":"项目不符提示"},
     * {"label":"8","content":"项目不符提示可强审"}
     */
    let vsNotEqualTips = getOptionValueByCodeRptGroupOption('jcsfxmybgxmsfxfclfs');
    console.log('系统选项参数', vsNotEqualTips);
    if ((vsNotEqualTips === '1' || vsNotEqualTips === 1) && resultList.length > 0 && !IsEmpty(mDictCount.value) && Number(feeVsItemDictCount.value) !== Number(resultList.length)) {
      const type = await VXETable.modal.confirm(`对照项目数量与检验结果数量不相等,是否审核?\n`); /*不能改el  $confirm 回车事件冒泡你*/
      if (type !== 'confirm') {
        return res;
      }
    }
    if ((vsNotEqualTips === '8' || vsNotEqualTips === 8) && resultList.length > 0 && !IsEmpty(mDictCount.value) && Number(feeVsItemDictCount.value) !== Number(resultList.length)) {
      const type = await VXETable.modal.confirm(`对照项目数量与检验结果数量不相等,是否审核?\n`); /*不能改el  $confirm 回车事件冒泡你*/
      if (type !== 'confirm') {
        return res;
      }
    }
    if ((vsNotEqualTips === '2' || vsNotEqualTips === 2) && resultList.length > 0 && !IsEmpty(mDictCount.value) && Number(feeVsItemDictCount.value) !== Number(resultList.length)) {
      const type = await VXETable.modal.confirm(`对照项目数量与检验结果数量不相等,禁止审核!!!\n`); /*不能改el  $confirm 回车事件冒泡你*/
      if (type !== 'confirm' || type === 'confirm') {
        return res;
      }
    }
    if ((vsNotEqualTips === '6' || vsNotEqualTips === 6) && resultList.length > 0 && !IsEmpty(mDictCount.value) && Number(feeVsItemDictCount.value) !== Number(resultList.length)) {
      const type = await VXETable.modal.confirm(`对照项目数量与检验结果数量不相等,禁止审核打印!!!\n`); /*不能改el  $confirm 回车事件冒泡你*/
      if (type !== 'confirm' || type === 'confirm') {
        return res;
      }
    }
    if ((vsNotEqualTips === '7' || vsNotEqualTips === 7) && resultList.length > 0 && !IsEmpty(mDictCount.value) && Number(feeVsItemDictCount.value) !== Number(resultList.length)) {
      const type = await VXETable.modal.confirm(`对照项目数量与检验结果数量不相等,是否继续?\n`); /*不能改el  $confirm 回车事件冒泡你*/
      if (type !== 'confirm') {
        return res;
      }
    }
    res = true;
  } catch (error) {}
  return res;
}
/**打印验证，项目对照，检验结果数量是否相等 */
async function printValidateVsCountIsEqual() {
  let res = false;
  try {
    /**对照项目、中间结果项不服是否提示的系统选项判断 jcsfxmybgxmsfxfclfs*/
    /**
     * {"label":"0","content":"不检查"},
     * {"label":"1","content":"审核时提示"},
     * {"label":"2","content":"禁止审核"},
     * {"label":"3","content":"打印时提示"},
     * {"label":"4","content":"禁止打印"},
     * {"label":"5","content":"打印审核时提示"},
     * {"label":"6","content":"禁止审核打印"},
     * {"label":"7","content":"项目不符提示"},
     * {"label":"8","content":"项目不符提示可强审"}
     */
    let vsNotEqualTips = getOptionValueByCodeRptGroupOption('jcsfxmybgxmsfxfclfs');
    console.log('系统选项参数', vsNotEqualTips);
    if ((vsNotEqualTips === '3' || vsNotEqualTips === 3) && resultList.length > 0 && !IsEmpty(mDictCount.value) && Number(feeVsItemDictCount.value) !== Number(resultList.length)) {
      const type = await VXETable.modal.confirm(`对照项目数量与检验结果数量不相等,是否打印?\n`); /*不能改el  $confirm 回车事件冒泡你*/
      if (type !== 'confirm') {
        return res;
      }
    }
    if ((vsNotEqualTips === '4' || vsNotEqualTips === 4) && resultList.length > 0 && !IsEmpty(mDictCount.value) && Number(feeVsItemDictCount.value) !== Number(resultList.length)) {
      const type = await VXETable.modal.confirm(`对照项目数量与检验结果数量不相等,禁止打印!!!\n`); /*不能改el  $confirm 回车事件冒泡你*/
      if (type !== 'confirm' || type === 'confirm') {
        return res;
      }
    }
    if ((vsNotEqualTips === '5' || vsNotEqualTips === 5) && resultList.length > 0 && !IsEmpty(mDictCount.value) && Number(feeVsItemDictCount.value) !== Number(resultList.length)) {
      const type = await VXETable.modal.confirm(`对照项目数量与检验结果数量不相等,是否继续?\n`); /*不能改el  $confirm 回车事件冒泡你*/
      if (type !== 'confirm') {
        return res;
      }
    }
    res = true;
  } catch (error) {}
  return res;
}
</script>
<style lang="scss" scoped>
#rptresult {
  height: 100%;

  .redClazz {
    color: red;
    margin-right: 5px;
  }

  .wjxmjg {
    font-size: 16px;
  }
}

/*:deep(.vxe-cell) {
  height: 100%;
}*/

/*
:deep(.vxe-input) {
  line-height: 100% !important;
  height: 100% !important;
}

:deep(.vxe-input--inner) {
  height: inherit !important;
  line-height: unset !important;
}*/

/*结果下拉选择*/
.my-dropdown5 {
  width: 450px;
  height: 300px;
  background-color: #fff;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

:deep(.wl-result-exmitem .el-input__inner) {
  height: 24px !important;
  line-height: 24px !important;
  border-radius: 0px !important;
  padding: 0 1px !important;
  width: 100%;
}
</style>
